package com.swak.boot.config.jdbc.mapper;

import java.util.List;
import java.util.Set;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import com.swak.boot.Application;
import com.swak.persistence.mybatis.enhance.EnhanceMapperFactoryBean;
import com.swak.utils.Lists;

public class MybatisMapperScannerRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        List<String> packages = this.resolveMapperModelPackages();
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
        builder.addPropertyValue("processPropertyPlaceHolders", true);
        builder.addPropertyValue("annotationClass", Mapper.class);
        builder.addPropertyValue("mapperFactoryBeanClass", EnhanceMapperFactoryBean.class);
        builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(packages));
        registry.registerBeanDefinition(MapperScannerConfigurer.class.getName(), builder.getBeanDefinition());
    }

    /**
     * 获取 Mappers -- Mapper 类
     * 
     * @return
     */
    public List<String> resolveMapperModelPackages() {
        List<String> _mapperLocations = Lists.newArrayList();
        Set<String> mapperLocations = Application.getScanPackages();
        for (String mapperLocation : mapperLocations) {
            if (!com.swak.utils.StringUtils.endsWith(mapperLocation, ".mapper")) {
                _mapperLocations.add(String.format("%s.**.mapper", mapperLocation));
            }
        }
        return _mapperLocations;
    }
}